package com.lzy.mall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.lzy.mall.common.utils.PageUtils;
import com.lzy.mall.product.entity.PmsBrand;
import com.lzy.mall.product.dao.PmsBrandDao;
import com.lzy.mall.product.service.PmsBrandService;
import com.lzy.mall.product.service.PmsCategoryBrandRelationService;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 品牌(PmsBrand)表服务实现类
 *
 * @author lzy
 * @since 2021-08-25 11:41:10
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class PmsBrandServiceImpl implements PmsBrandService {

    private final PmsBrandDao pmsBrandDao;

    private final PmsCategoryBrandRelationService categoryBrandRelationService;

    @Override
    public void save(PmsBrand pmsBrand) {
        pmsBrandDao.insertTemplate(pmsBrand);
    }

    @Override
    public PmsBrand getById(Long brandId) {
        return pmsBrandDao.single(brandId);
    }

    @Override
    public void removeByIds(List<Long> ids) {
        pmsBrandDao.createLambdaQuery()
                .andIn(PmsBrand::getBrandId,ids)
                .delete();
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        PageQuery pageQuery = new PageQuery();
        if (StrUtil.isNotBlank(key)){
            pageQuery.setPara("key",key);
        }

        PageQuery<PmsBrand> page = pmsBrandDao.queryPage(pageQuery);

        return new PageUtils(page);
    }

    @Override
    public void updateStatus(PmsBrand brand) {
        pmsBrandDao.updateTemplateById(brand);
    }

    @Override
    public List<PmsBrand> getBrandByIds(List<Long> brandIds) {
        List<PmsBrand> select = pmsBrandDao.createLambdaQuery()
                .andIn(PmsBrand::getBrandId, brandIds)
                .select();
        return select;
    }

    @Override
    @Transactional
    public void brandUpdate(PmsBrand pmsBrand) {
        // TODO 参数判断

        this.updateStatus(pmsBrand);
        if(!StrUtil.isEmpty(pmsBrand.getName())){
            //同步更新其他关联表中的数据
            categoryBrandRelationService.updateBrand(pmsBrand.getBrandId(),pmsBrand.getName());

            //TODO 更新其他关联
        }
    }
}
